document.addEventListener('DOMContentLoaded', () => {
  const rulesContainer = document.getElementById('rules-container');
  const addRuleButton = document.getElementById('add-rule');
  // Move enabledCheckbox initialization to where it's used, to ensure DOM is ready.
  let enabledCheckbox;

  let rules = [];

  const renderRules = () => {
    rulesContainer.innerHTML = '';
    if (rules.length === 0) {
        rulesContainer.innerHTML = '<p style="color: #888; text-align: center; font-size: 13px;">No rules yet. Add one below!</p>';
    }
    rules.forEach((rule, index) => {
      const ruleDiv = document.createElement('div');
      ruleDiv.className = 'rule';
      ruleDiv.innerHTML = `
        <input type="checkbox" ${rule.enabled ? 'checked' : ''}>
        <input type="text" value="${rule.from}" placeholder="e.g., 192.168.1.1:8080">
        <span class="arrow">→</span>
        <input type="text" value="${rule.to}" placeholder="e.g., localhost:8080">
        <button class="btn btn-delete" data-index="${index}">✕</button>
      `;
      rulesContainer.appendChild(ruleDiv);
    });
  };

  const extractHost = (url) => {
    try {
      // Handle URLs that may not have a protocol
      const urlWithProtocol = url.startsWith('http') ? url : `http://${url}`;
      const parsedUrl = new URL(urlWithProtocol);
      return parsedUrl.host;
    } catch (e) {
      // Return original string if it's not a valid URL
      return url;
    }
  };

  const saveState = () => {
    const ruleDivs = rulesContainer.querySelectorAll('.rule');
    const newRules = Array.from(ruleDivs).map(ruleDiv => {
      const fromInput = ruleDiv.querySelectorAll('input[type="text"]')[0];
      const toInput = ruleDiv.querySelectorAll('input[type="text"]')[1];
      const checkbox = ruleDiv.querySelector('input[type="checkbox"]');
      return {
        enabled: checkbox ? checkbox.checked : true,
        from: extractHost(fromInput.value.trim()),
        to: extractHost(toInput.value.trim()),
      };
    });
    rules = newRules;
    if (enabledCheckbox) {
      chrome.storage.sync.set({ rules: rules, enabled: enabledCheckbox.checked });
      chrome.runtime.sendMessage({ type: 'SET_RULES', rules });
    }
  };

  const loadState = () => {
    enabledCheckbox = document.getElementById('enabled');
    if (!enabledCheckbox) {
      console.error('Could not find the enabled checkbox.');
      return;
    }
    
    chrome.storage.sync.get(['rules', 'enabled'], (data) => {
      enabledCheckbox.checked = data.enabled !== false; // default to true
      rules = data.rules || [];
      if (rules.length === 0) {
        rules.push({ from: '192.168.31.242:8090', to: '127.0.0.1:8090', enabled: true });
        saveState();
      }
      renderRules();
    });
    
    enabledCheckbox.addEventListener('change', saveState);
  };
  addRuleButton.addEventListener('click', () => {
    rules.push({ from: '', to: '', enabled: true });
    renderRules();
    saveState();
  });

  rulesContainer.addEventListener('click', (e) => {
    if (e.target.classList.contains('btn-delete')) {
      const index = parseInt(e.target.dataset.index, 10);
      rules.splice(index, 1);
      renderRules();
      saveState();
    }
  });

  rulesContainer.addEventListener('change', saveState);
  rulesContainer.addEventListener('input', saveState);

  loadState();
});